import 'package:base_library/base_library.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'app/beans/models.dart';
import 'app/common/common.dart';
import 'app/common/sp_helper.dart';
import 'app/page/home_page.dart';
import 'app/page/splash_page.dart';
import 'app/page/welcome_page.dart';
import 'app/res/colors.dart';
import 'app/view/widget_progress.dart';

/**
 * StatefulWidget，通过调用setState({})方法来刷新控件
 */
class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  Locale _locale;
  Color _themeColor = Colours.app_main;
  @override
  void initState() {
    super.initState();
    _init();
    _loadLocale();
    initAsync();
  }

  void _init() {
//    DioUtil.openDebug();
//    Options options = DioUtil.getDefOptions();
//    options.baseUrl = Constant.server_address;
//    HttpConfig config = new HttpConfig(options: options);
//    DioUtil().setConfig(config);
  }

  void _loadLocale() {
    setState(() {
      LanguageModel model =
          SpHelper.getObject<LanguageModel>(Constant.keyLanguage);
      if (model != null) {
        _locale = new Locale(model.languageCode, model.countryCode);
      } else {
        _locale = null;
      }

      String _colorKey = SpHelper.getThemeColor();
      if (themeColorMap[_colorKey] != null)
        _themeColor = themeColorMap[_colorKey];
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      routes: {
        BaseConstant.routeMain: (ctx) => HomePage(),
      },
      //应用默认所显示的界面 Widget
      home: buildPage(),
      // 应用各种 UI 所使用的主题颜色
      theme: ThemeData.light().copyWith(
        primaryColor: _themeColor,
        accentColor: _themeColor,
        indicatorColor: Colors.white,
      ),
      locale: _locale,
    );
  }

  Widget buildPage() {
    switch (indexFlag) {
      case 0:
        return new ProgressView();
        break;
      case 1:
        return new SplashPage();
        break;
      case 2:
        return new WelcomePage();
        break;
    }
  }

  var indexFlag = 0;
  void initAsync() async {
    await SpUtil.getInstance();
    LogUtil.init(isDebug: true, tag: "reops");
    if (SpUtil.getBool(Constant.key_guide, defValue: true)) {
      //第一次打开软件 显示splash 页面
      var isSave = SpUtil.putBool(Constant.key_guide, false).toString();
      LogUtil.v("isSave " + isSave.toString());
      setState(() {
        indexFlag = 1;
      });
    } else {
      //多次打开页面 显示广告等待页面
      setState(() {
        indexFlag = 2;
      });
    }
  }
}
